package com.aqie.libfactory.presenter.message;


import com.alibaba.fastjson.JSONArray;
import com.aqie.libfactory.data.helper.MessageHelper;
import com.aqie.libfactory.data.message.MessageDataSource;
import com.aqie.libfactory.model.api.message.MsgCreateModel;
import com.aqie.libfactory.model.api.websocket.MessageDTO;
import com.aqie.libfactory.model.api.websocket.SendMessageModel;
import com.aqie.libfactory.model.api.websocket.WebsocketLoginModel;
import com.aqie.libfactory.model.db.Message;
import com.aqie.libfactory.persistence.Account;
import com.aqie.libfactory.presenter.BaseSourcePresenter;
import com.aqie.libfactory.utils.DiffUiDataCallback;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;

import java.util.List;
import java.util.UUID;

import androidx.recyclerview.widget.DiffUtil;

/**
 * 获取Websocket Manager 并进行登录
 * @param <View>
 */
@SuppressWarnings("WeakerAccess")
public class ChatPresenter<View extends ChatContract.View>
        extends BaseSourcePresenter<Message, Message, MessageDataSource, View>
        implements ChatContract.Presenter {

    // 接收者Id，可能是群，或者人的ID
    protected String mReceiverId;
    // 区分是人还是群Id
    protected int mReceiverType;

    WebSocketManager manager = null;
    public ChatPresenter(MessageDataSource source, View view,
                         String receiverId, int receiverType) {
        super(source, view);
        this.mReceiverId = receiverId;
        this.mReceiverType = receiverType;
        manager = WebSocketHandler.getDefault();
        // websocket登录
        WebsocketLoginModel loginModel = new WebsocketLoginModel();
        loginModel.setExpand(Account.getUserId());
        manager.send(JSONArray.toJSON(loginModel).toString());
    }

    @Override
    public void pushText(String content,boolean canTalk) {
        // 构建一个新的消息, 暂时用不到
        MsgCreateModel model = new MsgCreateModel.Builder()
                .receiver(mReceiverId, mReceiverType)
                .content(content, Message.TYPE_STR)
                .build();

        // websocket 进行网络发送
        MessageDTO msg = websocketSendMsg(content, canTalk);
        // 派发消息
        MessageHelper.push(msg);
    }

    // 发送消息
    private MessageDTO websocketSendMsg(String content, boolean canTalk) {
        SendMessageModel messageModel = new SendMessageModel();
        MessageDTO msg = new MessageDTO();
        msg.setMsg(content);
        msg.setStatus(canTalk ? Message.STATUS_DONE : Message.STATUS_FAILED);
        msg.setMsgId(UUID.randomUUID().toString());
        msg.setReceiverId(mReceiverId);
        msg.setSenderId(Account.getUserId());
        messageModel.setMessage(msg);
        if(canTalk){
            manager.send(JSONArray.toJSON(messageModel).toString());
        }
        return msg;
    }


    @Override
    public void onDataLoaded(List<Message> messages) {
        ChatContract.View view = getView();
        if (view == null)
            return;

        // 拿到老数据
        @SuppressWarnings("unchecked")
        List<Message> old = view.getRecyclerAdapter().getItems();

        // 差异计算
        DiffUiDataCallback<Message> callback = new DiffUiDataCallback<>(old, messages);
        final DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
        // Collections.reverse(messages);
        // 进行界面刷新
        refreshData(result, messages);
    }
}
